package com.example.diary;

import static com.example.diary.DatabaseHelper.TABLE_NAME;
import static com.example.diary.MainActivity.TAG_INSERT;
import static com.example.diary.MainActivity.TAG_UPDATE;
import static com.example.diary.MainActivity.TAG_GOBACK;
import static com.example.diary.MainActivity.dbHelper;
import static com.example.diary.MainActivity.getDbHelper;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.ByteArrayOutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zengzl
 * 照片环节容易出问题，先去掉照片的存储和读取
 */

public class Detail extends AppCompatActivity {
    private static final int PERMISSION_REQUEST = 1001;
    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA,Manifest.permission.CALL_PHONE,Manifest.permission.READ_EXTERNAL_STORAGE};
    List<String> permissionsList = new ArrayList<>();


    private SQLiteDatabase db;
    EditText title;  //标题
    TextView author; //作者
    TextView time;  //时间
    EditText content;//内容
    Button pictureChoice;//从相册选择照片
    private int i=0;
    ImageView picture;//照片
    public DatabaseHelper deHelper = getDbHelper();
    private int tag;
    private int id;
    private static final int CHOICE_PHOTO = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 隐藏状态栏 调试通过，写入ppt
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_detail);

        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        // 请求权限
        initPermissions();
        Intent intent = getIntent();
        String id_name = intent.getStringExtra("id_name");

        System.out.println("\n\n\n作者名" + id_name);
//        Toast.makeText(Detail.this, "日记详细列表一开始获取到的姓名为"+id_name, Toast.LENGTH_SHORT).show();

        title = findViewById(R.id.detail_title);
        author = findViewById(R.id.detail_author);
        time = findViewById(R.id.detail_time);
        content = findViewById(R.id.detail_content);
        pictureChoice=findViewById(R.id.detail_pictureChoice);
        picture=findViewById(R.id.detail_picture);
        title.setSelection(title.getText().length());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        time.setText(simpleDateFormat.format(date));
        author.setText("当前作者：" + id_name);
        content.setSelection(content.getText().length());

        //选择照片
        pictureChoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(Detail.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(Detail.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    openAlbum();
                }
            }
        });

        db = dbHelper.getWritableDatabase();

        tag = intent.getIntExtra("TAG", -1);
        switch (tag) {
            case TAG_INSERT:
                break;
            case TAG_UPDATE:
                id = intent.getIntExtra("ID", -1);
                Cursor cursor = db.query(TABLE_NAME, null, "id=?",
                        new String[]{String.valueOf(id)}, null, null, null);
                if (cursor.moveToFirst()) {
                    String select_title = cursor.getString(cursor.getColumnIndex("title"));
                    String select_author = cursor.getString(cursor.getColumnIndex("author"));
                    String select_content = cursor.getString(cursor.getColumnIndex("content"));
                    title.setText(select_title);
                    author.setText(select_author);
                    content.setText(select_content);
                    byte[] in = cursor.getBlob(cursor.getColumnIndex("picture"));
                    if(in != null){
                        Bitmap bitmap=BitmapFactory.decodeByteArray(in,0,in.length);
                        picture.setImageBitmap(bitmap);
                    }else{
                        System.out.println("todo 空指针异常优化");
                    }

                }
                break;
            case TAG_GOBACK:
                Intent intent1 = new Intent(Detail.this, MainActivity.class);
                startActivity(intent1);
                break;
        }
    }


    /**
     * 请求权限
     */
    private void initPermissions() {
        permissionsList.clear();

        //判断哪些权限未授予
        for(String permission : permissions){
            if(ActivityCompat.checkSelfPermission(this,permission)!= PackageManager.PERMISSION_GRANTED){
                permissionsList.add(permission);
            }
        }

        //请求权限
        if(!permissionsList.isEmpty()){
            String[] permissions = permissionsList.toArray(new String[permissionsList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(Detail.this, permissions, PERMISSION_REQUEST);
        }
    }


    //打开系统相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOICE_PHOTO);
    }

    //请求权限结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Toast.makeText(this, "你拒绝了权限申请", Toast.LENGTH_SHORT).show();
                }
                break;
            case PERMISSION_REQUEST:    //2021-11-25 请求权限回调
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOICE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    //对图片进行解析
    @TargetApi(31)
    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri =data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
                }
            }else if("content".equalsIgnoreCase(uri.getScheme())){
                imagePath = getImagePath(uri,null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagePath = uri.getPath();
            }
            displayImage(imagePath);
    }

//    图片显示前对图片进行解析
    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

//    获取图片的路径
    private String getImagePath(Uri uri, String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection,null, null);
        if(cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

//    显示照片
    private void displayImage(String imagePath){
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this,"failed to get image", Toast.LENGTH_SHORT).show();
        }
    }

    //将menu中的actionbar添加进来
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    //设置“保存”或者“删除”按钮点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        AlertDialog dialog;
        Intent intent = getIntent();
        String author_name = intent.getStringExtra("id_name");
        System.out.println("\n\n\n作者名" + author_name);
//        Toast.makeText(Detail.this, "日记详细列表获取到的姓名为"+author_name, Toast.LENGTH_SHORT).show();
        switch (item.getItemId()) {
            case R.id.save:
                if (tag == TAG_INSERT) {   //保存

                    ContentValues values = new ContentValues();
                    values.put("title", title.getText().toString());
                    values.put("author", author_name);
                    values.put("content", content.getText().toString());
                    //debug 2021-11-30 增加写入时间
                    values.put("time",time.getText().toString());
                    final ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (picture.getDrawable() != null) {
                        Bitmap bitmap = ((BitmapDrawable) picture.getDrawable()).getBitmap();
                        if (bitmap != null) {
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                            values.put("picture", os.toByteArray());
                        } else {
                            //todo 逻辑优化
                            System.out.println("空指针异常");
                        }
                    } else {
                        //todo 逻辑优化
                        System.out.println("无照片时的逻辑优化");
                    }
                    // 判断日记标题是否为空
                    if (title.length() == 0) {    //标题长度等于0，表示未输入任何字符
                        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                                .setTitle("警告")
                                //yh，替换图标done
                                .setIcon(R.mipmap.warn)
                                .setMessage("当前日记标题为空，请输入后再保存")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
//                                        values.put("picture",os.toByteArray());
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        dialog = builder.create();
                        dialog.show();
                        // debug 2021-11-21 dialog弹窗按钮字体颜色重现
                        Button btnPos = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                        Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                        btnPos.setTextColor(Color.RED);
                        btnNeg.setTextColor(Color.GRAY);
                    } else if (content.length() == 0) {    //判断内容是否为空,长度等于0，表示未输入任何字符
                        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                                .setTitle("警告")
                                //yh，替换图标done
                                .setIcon(R.mipmap.warn)
                                .setMessage("当前日记内容为空，请输入后再保存")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        dialog = builder.create();
                        dialog.show();
                        // debug 2021-11-21 dialog弹窗按钮字体颜色重现
                        Button btnPos = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                        Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                        btnPos.setTextColor(Color.RED);
                        btnNeg.setTextColor(Color.GRAY);
                    } else {
                        db.insert(TABLE_NAME, null, values);
                        values.clear();
                        // 调用Intent返回MainActivity页面，达成刷新的效果
                        Intent intentToMainActivity = new Intent(Detail.this, MainActivity.class);
                        intentToMainActivity.putExtra("id_name", author_name);
                        startActivity(intentToMainActivity);
                        //结束当前页面活动
                        finish();
                        Toast.makeText(Detail.this, "保存成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                } else if (tag == TAG_UPDATE) {  //更新
                    //修改title、content和picture
                    String update_title = title.getText().toString();
//                    String update_author = author_name;
                    String update_content = content.getText().toString();
                    final ContentValues values = new ContentValues();
                    values.put("title", update_title);
//                    values.put("author", update_author);
                    values.put("content", update_content);
                    final ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (picture.getDrawable() != null) {
                        Bitmap bitmap = ((BitmapDrawable) picture.getDrawable()).getBitmap();
                        if (bitmap != null) {
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                            values.put("picture",os.toByteArray());
                        } else {
                            //todo 逻辑优化
                            System.out.println("无照片时的逻辑优化");
                        }
                    } else {
                        //todo 逻辑优化
                        System.out.println("无照片时的逻辑优化");
                    }
                        if (title.length() == 0) {    // 判断日记标题是否为空,标题长度等于0，表示未输入任何字符
                            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                                    .setTitle("警告")
                                    //yh，替换图标done
                                    .setIcon(R.mipmap.warn)
                                    .setMessage("当前日记标题为空，请输入后再保存")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            values.put("picture", os.toByteArray());
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    });
                            dialog = builder.create();
                            dialog.show();
                            // debug 2021-11-21 dialog弹窗按钮字体颜色重现
                            Button btnPos = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                            Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                            btnPos.setTextColor(Color.RED);
                            btnNeg.setTextColor(Color.GRAY);
                        } else if (content.length() == 0) {    //判断内容是否为空,长度等于0，表示未输入任何字符
                            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                                    .setTitle("警告")
                                    //yh，替换图标done
                                    .setIcon(R.mipmap.warn)
                                    .setMessage("当前日记内容为空，请输入后再保存")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            values.put("picture", os.toByteArray());
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    });
                            dialog = builder.create();
                            dialog.show();
                            // debug 2021-11-21 dialog弹窗按钮字体颜色重现
                            Button btnPos = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                            Button btnNeg = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                            btnPos.setTextColor(Color.RED);
                            btnNeg.setTextColor(Color.GRAY);
                        } else {
                            db.update(TABLE_NAME, values, "id=?", new String[]{String.valueOf(id)});
                            values.clear();
                            // 调用Intent返回MainActivity页面，达成刷新的效果
                            Intent intentToMain = new Intent(Detail.this, MainActivity.class);
                            startActivity(intentToMain);
                            //结束当前页面活动
                            finish();
                            Toast.makeText(Detail.this, "更新成功", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    case R.id.delete:
                        if (tag == TAG_UPDATE) {
                            db.delete(TABLE_NAME, "id=?", new String[]{String.valueOf(id)});
                        }
                        Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                        // 调用Intent返回MainActivity页面，达成刷新的效果
                        Intent intentToMain = new Intent(this, MainActivity.class);
                        startActivity(intentToMain);
                        //结束当前页面活动
                        finish();
                        break;
                    case R.id.goBack:
                        //debug 2021-11-30 返回页面逻辑优化
                        Intent intent_goBack = new Intent(this, MainActivity.class);
                        intent_goBack.putExtra("id_name",author_name);
                        startActivity(intent_goBack);
                        //结束当前页面活动
                        finish();
                        break;
                    default:
                }
                return true;
        }
    }
